//
//  RegisterUserViewController.m
//  JHFBaseProject
//
//  Created by 计海峰 on 16/4/22.
//  Copyright © 2016年 好牛. All rights reserved.
//

#import "RegisterUserViewController.h"

@interface RegisterUserViewController ()
{
    __weak IBOutlet UIButton *l_timeButton;
    
    NSString *registerPhone;
    //1 找回密码
    NSInteger _flag;
    //
}
@end

@implementation RegisterUserViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (instancetype)initWithFlag:(NSInteger)flag
{
    self = [super init];
    if (self) {
        _flag = flag;
    }
    return self;
}
-(void)drawView{
    [_sendCode setBackgroundColor: RGB(254, 194, 54)];
    _sendCode.layer.masksToBounds = YES;
    _sendCode.layer.cornerRadius = _sendCode.frame.size.height/2;
    [_loginBtn setBackgroundColor:RGBJ(128)];
    _loginBtn.layer.masksToBounds = YES;
    _loginBtn.layer.cornerRadius = _loginBtn.frame.size.height/2;
    
    
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGColorRef color = CGColorCreate(colorSpaceRef, (CGFloat[]){226.0/255.0,226.0/255.0,226.0/255.0,1});
    
    _codeView.layer.masksToBounds = YES;
    _codeView.layer.cornerRadius = 1;
    _codeView.layer.borderColor = color;
    _codeView.layer.borderWidth = 1;
    
    _userIdView.layer.masksToBounds = YES;
    _userIdView.layer.cornerRadius = 1;
    _userIdView.layer.borderColor = color;
    _userIdView.layer.borderWidth = 1;
    
    _telView.layer.masksToBounds = YES;
    _telView.layer.cornerRadius = 1;
    _telView.layer.borderColor = color;
    _telView.layer.borderWidth = 1;
    
    _pwdView.layer.masksToBounds = YES;
    _pwdView.layer.cornerRadius = 1;
    _pwdView.layer.borderColor = color;
    _pwdView.layer.borderWidth = 1;
    if (_flag == 1){
        self.title = @"修改密码";
//        _delegateView.hidden = YES;
    }
    else{
        self.title = @"注册";
    }
}


- (IBAction)backAction:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}



- (IBAction)iconStateAction:(UIButton *)sender {
    _iconBtn.selected = !_iconBtn.selected;
    if (_iconBtn.selected) {
        [_iconBtn setBackgroundImage:[UIImage imageNamed:@"selected_2.png"] forState:UIControlStateNormal];
    
           [_loginBtn setBackgroundColor:RGB(91, 188, 81)];
    }else{
      [_iconBtn setBackgroundImage:[UIImage imageNamed:@"selected_1.png"] forState:UIControlStateNormal];
         [_loginBtn setBackgroundColor:RGBJ(128)];
    }
    
}


- (IBAction)registerUser {
    
    if (!_iconBtn.selected) {
        [self showHint:@"请阅读白大夫协议"];
        return;
    }
    
//    if (!registerPhone) {
//        E(@"请先获取验证码");
//        return;
//    }
    if (!_invateCode.text) {
      [self showHint:@"请先获取邀请码"];
        return;
    }
    if (![_phone.text isMobileNumber]) {
        [self showHint:@"手机号码格式不正确"];
        return;
    }
    if (![_verificationCode.text isVerifyNum:6]) {
        [self showHint:@"验证码错误"];
        return;
    }
    if (![_password.text isPassWord]) {
        [self showHint:@"密码长度在6~16位"];
        return;
    }
    

    if (_flag == 1){
//        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:registerPhone,@"loginName",_password.text,@"passWord",_verificationCode.text , @"code",nil];
//        [AFNetworkTool  NetWorkRequest:@"mobile/user/amendPassWord" parameters:param WithSuceessMessage:@"注册成功" WithMethod:@"modifySuccess:" WithController:self AndInfoView:self.view];
    }else{
        NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:_phone.text,@"username",_password.text,@"password",_verificationCode.text,@"captcha",_invateCode.text , @"inviteCode",nil];
        [param setObject:@"0" forKey:@"isDoctor"];
        NSLog(@"param = %@",param);
        
        
        AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:url_Register parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSError * error;
            NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
            [self hideHud];
            if (error) {
                NSLog(@"====error1:%@",error);
                [self showHint:@"获取详情失败"];
                return;
            }
            NSLog(@"==dict:%@",data);
            NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
            if ([result isEqualToString:@"1"]) {
                  NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"obj"]];
                
                [self.navigationController popViewControllerAnimated:YES];
                
                NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
                [self showHint:info];
            }else{
                NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
                [self showHint:info];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
            NSLog(@"====error:%@",error);
            [self hideHud];
            [self showHint:@"注册失败"];
        }];

        
    }
}

//修改密码成功
-(void)modifySuccess:(NSDictionary *)result{
    if (result) {
        [self showHint:@"修改密码成功"];
//        USERDEFAULTS.userModel.userPassword = _password.text;
//        [self.navigationController popViewControllerAnimated:YES];
    }
}

//注册成功
-(void)registerSuccess:(NSDictionary *)result{
    NSLog(@"result = %@",result);
    if (result) {
        [self showHint:@"注册成功"];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
//是否同意
- (IBAction)isAgreeDelegate:(UIButton *)sender {
    sender.selected = !sender.selected ;
    
}






//获取验证码
-(void)getVerifyCode{
    [_verificationCode becomeFirstResponder];
    if (![_phone.text isMobileNumber]) {
        [self showHint:@"手机号码格式不正确"];
        return;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:_phone.text,@"phone" ,nil];
  

    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_code parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取详情失败"];
            return;
        }
        NSLog(@"==dict:%@",data);
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
      
            [self showHint:@"获取验证码成功"];
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"注册失败"];
    }];
}


//获取验证码成功
-(void)getCodeSuccess:(NSString*)result{
    registerPhone = _phone.text;
}

- (IBAction)startTime {

    if (![_phone.text isMobileNumber]) {
        [self showHint:@"手机号码格式不正确"];
        return;
    }
    [self getVerifyCode];
    __block int timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [l_timeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                l_timeButton.userInteractionEnabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [l_timeButton setTitle:[NSString stringWithFormat:@"已发送(%@)",strTime] forState:UIControlStateNormal];
                l_timeButton.userInteractionEnabled = NO;
                
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}



@end
